//index.js
//获取应用实例
var util = require("../../utils/util.js");
const RuiToast = require('../../components/toast/RuiToast.js');
var app = getApp();
Page({
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 5500,
    duration: 1500,
    loadingMore: false, // loading中
    isEnd: false, //到底啦
    userInfo: {},
    swiperCurrent: 0,
    // recommendTitlePicStr: '',
    categories: [],

    goodsList: [], //按类别的商品
    goods: [],
    recommendGoods: [], //推荐商品
    recommendGoodsShow: [], //显示的推荐商品，为了缓解网络加载压力设置每次加载15个推荐商品
    banners: [],

    loadingFinish: false,
    page: 1, //加载商品时的页数默认为1开始,在app页面加载
    pageSize: [], //每页商品数设置为5000确保能全部加载商品，在app页面加载
    stv: {
      windowWidth: 0,
      windowHeight: 0,
    },
    height: [],
    tejiaGoods: [],
    // bannerGoods:[],
    youhuiquan: false, //新人优惠券


    shopCarInfo: {}, //购物车数据
    tabScroll: 0, //使得导航位置居中
    tabs: [{
      _id: 0,
      name: "热销推荐"
    }],
    activeTab: 0,
  },

  onLoad: function () {
    
    this.setData({
      navH: app.globalData.navHeight
    });

    let userid = wx.getStorageSync('userid')
    if (!userid) {
      wx.navigateTo({
        url: "/pages/login/index"
      })
    }

    var that = this
    that.setData({
      goodsList: app.globalData.goodsList,
      goods: app.globalData.goods,
      pageSize: 10,
      page: 0,
      recommendGoodsShow: [],
      background_color: app.globalData.globalBGColor,
      bgRed: app.globalData.bgRed,
      bgGreen: app.globalData.bgGreen,
      bgBlue: app.globalData.bgBlue
    })

    const db = wx.cloud.database()
    db.collection('categories').orderBy('paixu', 'asc').get({
      success: res => {

        let tsbs1 = this.data.tabs.concat(res.data)
        this.setData({
          tabs: tsbs1
        })
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
    wx.setNavigationBarTitle({
      title: '首页',
    })
    that.getCouponsMarket()
    try {
      var res = wx.getSystemInfoSync()
      if (that.data.noticeList) {
        that.setData({
          stv: {
            windowsWidth: res.windowWidth,
            windowsHeight: res.windowHeight
          },
          height: (750 / res.windowWidth) * res.windowHeight - 100
        })
      } else {
        that.setData({
          stv: {
            windowsWidth: res.windowWidth,
            windowsHeight: res.windowHeight
          },
          height: (750 / res.windowWidth) * res.windowHeight
        })
      }

    } catch (e) {}



  },
  onShow: function () {
    var that = this
    
    let userid = wx.getStorageSync('userid')
   let userInfo = wx.getStorageSync('userInfo')
    if (userid) {
      
      //有userid依然登录
      //检查是否改变角色
      wx.cloud.callFunction({
        name: 'login1',
        data: {
          nickName:userInfo.nickName,
          gender:userInfo.gender,
          language:userInfo.language,
          city:userInfo.city,
          province:userInfo.province,
          country:userInfo.country,
          avatarUrl:userInfo.avatarUrl,
          dateAdd: new Date(),
          status:1//正常状态
        }
      }).then(res => {


        //  console.log(res)
        if (res.result.user.data[0].isManager == 1) {
          app.globalData.openid = res.result.openid
          app.globalData.isManager = res.result.user.data[0].isManager
          wx.setStorageSync('openid', res.result.openid); //存储openid  

          wx.setStorageSync('userid', res.result.user.data[0]._id); //存储openid 
          wx.reLaunch({
            url: '../sys/manager/index/index',
          })
          return
        } else if (res.result.user.data[0].isManager == 2) {
          app.globalData.openid = res.result.openid
          app.globalData.isManager = res.result.user.data[0].isManager
          wx.setStorageSync('openid', res.result.openid); //存储openid  

          wx.setStorageSync('userid', res.result.user.data[0]._id); //存储 
          wx.reLaunch({
            url: '../sys/manager/index/index',
          })
          return
        } else {
          //设置openid
          
          app.globalData.openid = res.result.openid
          app.globalData.isManager = res.result.user.data[0].isManager
          app.globalData.isnewUser = res.result.user.data[0].isnewUser
          wx.setStorageSync('openid', res.result.openid); //存储openid  
          wx.setStorageSync('userid', res.result.user.data[0]._id); //存储openid 


          wx.setStorageSync('isnewUser', res.result.user.data[0].isnewUser); //存储
          wx.reLaunch({
            url: '/TianguoguoXiaopu-master/pages/choiceness/index',
          })
          //自动加优惠券
          if (res.result.isnewUsr) {
            
            that.globalData.isnewUsr = true
          }


        }
      })
    }else{
      wx.navigateTo({
        url: '../login/index',
      })
    }
    //  if (app.globalData.isManager==1 ||app.globalData.isManager==2 ) {
    //    wx.redirectTo({
    //      url: "/pages/sys/manager/index/index"
    //    })
    //    return
    //  } 
    // 获取购物车数据
    wx.getStorage({
      key: 'shopCarInfo',
      success: function (res) {
        that.setData({
          shopCarInfo: res.data,
          shopNum: res.data.shopNum
        });
      }
    })
    that.getNotice(); //查询 快报
   
    that.getGoods(0)

  },
  //查询有效发放的优惠券
  getCouponsMarket() {
    let that = this
    that.setData({
      youhuiquanPutong: false //置空数据
    })
    wx.cloud.callFunction({
        // 云函数名称
        name: 'getcouponMarket',
        // 传给云函数的参数
        data: {

        },
      })
      .then(res => {
        let coupon = res.result.data
        let putongcoupon = []
        if (coupon.length > 0) {
          for (let dex = 0; dex < coupon.length; dex++) {
            const element = coupon[dex];
            if (element.leixing == 2) {
              that.setData({
                youhuiquan: element
              })
              //有新人优惠券，且用户没领过
              if (wx.getStorageSync('isnewUser')) {
                that.youhuiquanModel()

              }
            } else {
              putongcoupon.push(element)
              that.setData({
                youhuiquanPutong: putongcoupon
              })
            }
          }


        }
      })
  },
  //领取普通优惠券
  lingquyouhuiquan(e) {
    var that = this
    let id = e.currentTarget.dataset.id;
    const db = wx.cloud.database()
    db.collection('coupons').add({
      data: {
        dateAdd: new Date(),
        couponsMarketid: id,
        dateEnd: util.getdeadline(e.currentTarget.dataset.youxiaoqi),
        money: e.currentTarget.dataset.preferentialamount,
        moneyHreshold: e.currentTarget.dataset.moneyhreshold,
        name: e.currentTarget.dataset.couponname,
        status: 0,
      },
      success: function (res) {
        wx.showModal({
          title: '提示',
          content: '已成功领取优惠券',
        })
        //再查优惠券
        that.getCouponsMarket()

      },
      fail: err => {
        console.log(err)
      }
    })
  },
  //添加新人优惠券
  oncreateCoupons: function (e) {
    var that = this

    const db = wx.cloud.database()
    db.collection('coupons').add({
      data: {
        dateAdd: new Date(),
        couponsMarketid: that.data.youhuiquan._id,
        dateEnd: util.getdeadline(that.data.youhuiquan.youxiaoqi),
        money: that.data.youhuiquan.preferentialamount,
        moneyHreshold: that.data.youhuiquan.moneyHreshold,
        name: that.data.youhuiquan.couponname,
        status: 0,
      },
      success: function (res) {
        wx.showModal({
          title: '提示',
          content: '已成功领取优惠券',
        })
        RuiToast.hideToastModal(that, "#toast");
        wx.setStorageSync('isnewUser', false)
        db.collection('user').doc(wx.getStorageSync('userid')).update({
          data: {
            isnewUser: false
          },
          success: function (res) {

          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  //点击tabs切换
  onTabCLick(e) {

    this.setData({
      recommendGoods: [],
      recommendGoodsShow: [],
      isEnd: false,

    })

    let index = 0
    if (e && e.detail.index) {
      index = e.detail.index
    }
    this.setData({
      activeTab: index
    })

    if (index == 0) {
      //查推荐商品
      this.getAppRecommendGoodsList()
    } else {
      let goods = this.data.goods

      let recommendGoods = []
      for (let i = 0; i < goods.length; i++) {
        if (goods[i].categoryId == this.data.tabs[index]._id) {
          recommendGoods.push(goods[i])
        }
      }
      this.setData({
        recommendGoods: recommendGoods
      })
      //分页展示
      this.getRGshow()

    }
  },

  //上拉
  onReachBottom: function () {
    //console.log("上拉加载分页")
    var that = this
    that.getRGshow()
  },
  //下拉
  onPullDownRefresh: function () {
    var that = this
    that.setData({
      loadingMore: true,
      isEnd: false
    })
    wx.showNavigationBarLoading()
    that.onShow()


    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */

  onShareAppMessage: function () {
    return {
      title: wx.getStorageSync('mallName') + '——' + app.globalData.shareProfile,
      path: '/pages/choiceness/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  //事件处理函数
  swiperchange: function (e) {

    this.setData({
      swiperCurrent: e.detail.current
    })
  },

  //加入购物车
  addShopCar(event) {

    var id = event.currentTarget.dataset.id;
    //查库存
    const db = wx.cloud.database()
    db.collection('goods').where({
      _id: id
    }).get({
      success: res => {

        if (res.data[0].stores > 0) {
          //组建购物车
          var shopCarInfo = this.bulidShopCarInfo(event);
          this.setData({
            shopCarInfo: shopCarInfo,
            shopNum: shopCarInfo.shopNum
          });
          // 写入本地存储
          wx.setStorage({
            key: "shopCarInfo",
            data: shopCarInfo
          })

          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 1000
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '库存不足！',
            showCancel: false
          })
          return
        }
      }
    })
  },
  //组件购物车
  bulidShopCarInfo: function (event) {

    // 加入购物车
    var shopCarMap = {};
    shopCarMap.goodsId = event.currentTarget.dataset.id;
    shopCarMap.pic = event.currentTarget.dataset.pic;
    shopCarMap.name = event.currentTarget.dataset.name;
    // shopCarMap.label=this.data.goodsDetail.id; 规格尺寸 
    shopCarMap.propertyChildIds = event.currentTarget.dataset.propertychildids || "";
    //  shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = event.currentTarget.dataset.minprice;
    //  shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = 1; // this.data.buyNumber;
    //  shopCarMap.logisticsType = this.data.goodsDetail.logisticsId;
    // shopCarMap.logistics = this.data.goodsDetail.logistics;
    //shopCarMap.weight = this.data.goodsDetail.weight;

    // 获取购物车数据
    var shopCarInfo = this.data.shopCarInfo;
    if (!shopCarInfo.shopNum) {
      shopCarInfo.shopNum = 0;
    }
    if (!shopCarInfo.shopList) {
      shopCarInfo.shopList = [];
    }
    var hasSameGoodsIndex = -1;
    for (var i = 0; i < shopCarInfo.shopList.length; i++) {
      var tmpShopCarMap = shopCarInfo.shopList[i];

      if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
        hasSameGoodsIndex = i;
        shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
        break;
      }
    }

    shopCarInfo.shopNum = shopCarInfo.shopNum + 1;
    if (hasSameGoodsIndex > -1) {
      shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
    } else {
      shopCarInfo.shopList.push(shopCarMap);
    }
    //shopCarInfo.kjId = this.data.kjId;

    return shopCarInfo;



  },
  //点击商品
  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  //点击轮播图跳转
  tapBanner: function (e) {

    if (e.currentTarget.dataset.type == 1) {
      if (e.currentTarget.dataset.goodsid) {
        wx.navigateTo({
          url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.goodsid
        })
      }
    } else if (e.currentTarget.dataset.type == 2) {
      if (e.currentTarget.dataset.goodsids) {
        wx.navigateTo({
          url: "/pages/huodong/huodong?id=" + e.currentTarget.dataset.id
        })
      }

    }

  },

  //获取特价
  getTejiaGoodsList() {

    var that = this
    var goods = that.data.goods

    var tejiaGoods = []
    for (let i = 0; i < goods.length; i++) {

      if (goods[i].tejia === 1) {
        tejiaGoods.push(goods[i])
      }
    }
    that.setData({
      tejiaGoods: tejiaGoods
    })

  },

  getNotice: function () {

    var that = this;
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('noticeList').orderBy('dateAdd', 'desc').get({
      success: res => {
        ///console.log(res)
        this.setData({
          noticeList: res.data
        })

      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })

  },
  //轮播图
  // getBanners: function () {
  //   var that = this

  //   const db = wx.cloud.database()
  //   db.collection('banners').where({
  //     status: 1
  //   }).get({
  //     success: res => {
  //       let banners = res.data
  //       that.setData({
  //         banners: banners
  //       })
  //     }
  //   })
  // },
  // 从app页面的goodsList中获取推荐商品
  getAppRecommendGoodsList: function () {

    var that = this
    var goods = that.data.goods

    var recommendGoods = []
    for (let i = 0; i < goods.length; i++) {

      if (goods[i].recommendStatus == 1) {
        recommendGoods.push(goods[i])
      }
    }
    that.setData({
      recommendGoods: recommendGoods
    })
    //精品推荐模拟分页展示
    that.getRGshow()
  },
  //精品推荐分页展示
  getRGshow: function () {

    console.log("加载下页")
    var that = this;
    if (that.data.isEnd) {
      // console.log('isEnd, return...')
      return;
    }
    //console.log('notEnd, continue')
    that.setData({
      loadingMore: true
    })
    var pageSize = 10; //一次加载万所有的推荐商品，避免minui显示问题that.data.recommendGoods.length
    var recommendGoodsShow = that.data.recommendGoodsShow;
    var rgShowLen = recommendGoodsShow.length;


    if (rgShowLen + pageSize <= that.data.recommendGoods.length) {
      for (var i = rgShowLen; i < rgShowLen + pageSize; i++) {
        recommendGoodsShow.push(that.data.recommendGoods[i])
      }


      that.setData({
        recommendGoodsShow: recommendGoodsShow
      })

      if (recommendGoodsShow.length < that.data.recommendGoods.length) {
        that.setData({
          loadingMore: false, //关闭遮罩层

        })
      } else {
        that.setData({
          loadingMore: false, //关闭遮罩层
          isEnd: true
        })
      }

    } else if (rgShowLen < that.data.recommendGoods.length) {
      for (var i = rgShowLen; i < that.data.recommendGoods.length; i++) {
        recommendGoodsShow.push(that.data.recommendGoods[i])
      }
      //虚拟加载特效

      that.setData({
        recommendGoodsShow: recommendGoodsShow,
        loadingMore: false, //关闭遮罩层
        isEnd: true //显示没有了提示
      })


    } else {
      that.setData({
        recommendGoodsShow: recommendGoodsShow,
        loadingMore: false, //关闭遮罩层
        isEnd: true //显示没有了提示
      })
    }
  },

  handlerStart(e) {

    let {
      clientX,
      clientY
    } = e.touches[0];
    this.startX = clientX;
    this.tapStartX = clientX;
    this.tapStartY = clientY;
    this.data.stv.tStart = true;
    this.tapStartTime = e.timeStamp;
    this.setData({
      stv: this.data.stv
    })
  },
  handlerMove(e) {

    let {
      clientX,
      clientY
    } = e.touches[0];
    let {
      stv
    } = this.data;
    let offsetX = this.startX - clientX;
    this.startX = clientX;
    stv.offset += offsetX;
    if (stv.offset <= 0) {
      stv.offset = 0;
    } else if (stv.offset >= stv.windowWidth * (this.tabsCount - 1)) {
      stv.offset = stv.windowWidth * (this.tabsCount - 1);
    }
    this.setData({
      stv: stv
    });
  },
  headerSearch() {
    if (this.properties.disableSearchJump) return
    wx.navigateTo({
      url: '/pages/search/index'
    })
  },
  handlerCancel(e) {

  },
  handlerEnd(e) {

    let {
      clientX,
      clientY
    } = e.changedTouches[0];
    let endTime = e.timeStamp;
    let {
      tabs,
      stv,
      activeTab
    } = this.data;
    let {
      offset,
      windowWidth
    } = stv;
    //快速滑动
    if (endTime - this.tapStartTime <= 300) {

      //判断是否左右滑动(竖直方向滑动小于50)
      if (Math.abs(this.tapStartY - clientY) < 50) {
        //Y距离小于50 所以用户是左右滑动
        //console.log('竖直滑动距离小于50')
        if (this.tapStartX - clientX > 5) {
          //向左滑动超过5个单位，activeTab增加
          //console.log('向左滑动')

        } else if (clientX - this.tapStartX > 5) {
          //向右滑动超过5个单位，activeTab减少
          //console.log('向右滑动')

        }
        stv.offset = stv.windowWidth * activeTab;
      } else {
        //Y距离大于50 所以用户是上下滑动
        //console.log('竖直滑动距离大于50')

      }
    } else {

    }
    stv.tStart = false;
    this.setData({
      stv: this.data.stv
    })
  },
  //弹窗领取优惠券
  youhuiquanModel(e) {
    this.setData({
      selftext: "selfcontent"
    });
    RuiToast.showToast({
      type: 'mask',
      closeStyle: 'right:auto;top:auto;bottom:-15vw;left:50%;transform:translateX(-50%)',
      closeShow: true,
      native: false,

    })
  },
  //查询所有商品
  getGoods: function () {

    var that = this;

    that.setData({
      loadingStatus: true
    })

    wx.cloud.callFunction({
        // 云函数名称
        name: 'crud',
        // 传给云函数的参数
        data: {
          db: "goods",
          type: "getall",
          data: "",
          indexKey: "",
          //待筛选的参数-库存 >0
          commandtype: [{
            type: 'gt',
            ziduan: 'stores',
            value: 0
          }],
          condition: {
            status: 1 //状态1
          },
        },
      })
      .then(res => {

        that.setData({
          goods: [],
        });
        var goods = [];

        if (res.result) {
          if (res.result.data.length == 0) {
            that.setData({

              loadingMore: false,
              isEnd: true,
              loadingStatus: false
            })
            return;
          }
          let result = res.result.data
          for (var i = 0; i < result.length; i++) {
            result[i].minPrice = result[i].minPrice.toFixed(2);
            result[i].originalPrice = result[i].originalPrice.toFixed(2);

            goods.push(result[i]);
          }

          // app.globalData.goods = goods

          //赋值当前页面的goods
          that.setData({
            goods: goods,
          });

          that.setData({
            loadingStatus: false,
            loadingFinish: true
          })
          that.onTabCLick()
          that.getTejiaGoodsList() //从global数据中获取特价商品
          setTimeout(() => {
            that.setData({
              loadingFinish: false
            })
          }, 1500)

        }
      })
      .catch(console.error)

  },
})